package com.yishusmt.wechatapi.wechatdev.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云OSS文件操作
 *
 */
@PropertySource(value = "classpath:oss.properties")
@Slf4j
@Component
public class AliyunOSSUtil {

    @Value("${java4all.file.endpoint}")
    private String endpoint;

    @Value("${java4all.file.keyid}")
    private String accessKeyId;

    @Value("${java4all.file.keysecret}")
    private String accessKeySecret;

    @Value("${java4all.file.bucketname1}")
    private String bucketName;

    @Value("${java4all.file.filehost}")
    private String fileHost;

    public String upload(File file){
        log.info("OSS文件上传开始："+file.getName());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_kk:mm:ss");
        String dateStr = format.format(new Date());
        if(null == file && !file.exists()){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //创建文件路径
            String fileUrl = fileHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                log.info("OSS文件上传成功,OSS地址："+fileUrl);
                return fileUrl;
            }
        }catch (OSSException oe){
            log.error(oe.getMessage());
        }catch (ClientException ce){
            log.error(ce.getMessage());
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }


    /**
     * 文件下载
     *
     * @param objectName
     */
    public String download(String objectName){
        log.info("");
        return null;
    }

    /**
     * 删除文件
     *
     * @param objectName
     * @return
     */
    public String detele(String objectName){
        log.info("删除文件");


        return null;
    }
}
